package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.apuser.IApUserClient;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.pojos.CommentRepayVo;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.pojos.UpdateArticleInfo;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IWemediaClient wemediaClient;
    @Autowired
    private IApUserClient apUserClient;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 保存回复评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //1.校验参数
        if (dto == null || StringUtils.isBlank(dto.getContent()) || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录
        ApUser apUser = ApUserThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //判断回复是否大于140字
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容大于140字");
        }
        //5.检测评论内容是否为垃圾文本
        Map<String, String> resultMap = wemediaClient.scanText(dto.getContent());
        String conclusionType = resultMap.get("conclusionType");
        if (!"1".equals(conclusionType)) {
            //文本审核不通过
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取用户信息
        ApUser user = apUserClient.findUserById(apUser.getId());
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存回复评论
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());

        mongoTemplate.save(apCommentRepay);
        Query query = Query.query(Criteria.where("_id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query,ApComment.class);
        if (apComment==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (apComment.getReply()==null){
            apComment.setReply(0);
        }
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);
        //更新文章信息
        UpdateArticleInfo updateArticleInfo = new UpdateArticleInfo();

//        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
//        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
//        if (apComment!=null)
        //获取文章ID
            updateArticleInfo.setArticleId(apComment.getEntryId());
        updateArticleInfo.setComment(1);
        kafkaTemplate.send(ArticleConstants.ARTICLE_SCORE_TOPIC, JSON.toJSONString(updateArticleInfo));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询评论回复列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //参数校验
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页默认10条数据
        int count = 10;
        //查询数据
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        query.with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(count);
        List<ApCommentRepay> list = mongoTemplate.find(query, ApCommentRepay.class);
        //检查是否为游客登录
        ApUser user = ApUserThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.okResult(list);
        }
        //用户以登录,返回用户点赞回复评论集合
        List<String> commentRepayIdLists = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : list) {
            commentRepayIdLists.add(apCommentRepay.getId());
        }
        //查询当前用户点赞的数据
        Query likesQuery = Query.query(Criteria.where("commentRepayId").in(commentRepayIdLists).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> likesLists = mongoTemplate.find(likesQuery, ApCommentRepayLike.class);
        //将回复评论里全部都没点赞的返回
        if (likesLists == null || likesLists.size() == 0) {
            return ResponseResult.okResult(list);
        }
        List<CommentRepayVo> resultList = new ArrayList<>();
        //设置点赞状态
        short operation = 0;
        //遍历回复集合，将点赞状态加入到集合中
        for (ApCommentRepay apCommentRepay : list) {
            CommentRepayVo commentRepayVo = new CommentRepayVo();
            BeanUtils.copyProperties(apCommentRepay, commentRepayVo);
            for (ApCommentRepayLike likesList : likesLists) {
                if (apCommentRepay.getId().equals(likesList.getCommentRepayId())) {
                    commentRepayVo.setOperation(operation);
                    break;
                }
            }
            resultList.add(commentRepayVo);
        }
        return ResponseResult.okResult(resultList);
    }


    /**
     * 回复评论点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likeCommentRepay(CommentRepayLikeDto dto) {
        //校验参数
        if (dto == null || dto.getCommentRepayId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //登录检测
        ApUser user = ApUserThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        //1.点赞
        //2.取消点赞
        if (apCommentRepay != null && dto.getOperation() == 1) {
            //点赞状态更新
//            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
//            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
//            apCommentRepayLike.setOperation(null);
//            apCommentRepayLike.setAuthorId(user.getId());

            //将点赞记录删除
            Query query = Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId()).and("authorId").is(user.getId()));
            mongoTemplate.remove(query, ApCommentRepayLike.class);
            //更新点赞数
            Integer likes = apCommentRepay.getLikes() - 1;
            apCommentRepay.setLikes(likes < 1 ? 0 : likes);
            mongoTemplate.save(apCommentRepay);
            //3.点赞
        } else {
            //点赞状态更新
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation((short) 0);
            apCommentRepayLike.setAuthorId(user.getId());
            mongoTemplate.save(apCommentRepayLike);
            //更新点赞数
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepay);
        }
        //返回参数
        Map<String, Integer> resultMap = new HashMap<>();
        resultMap.put("likes", apCommentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
